{% extends 'admin/admin_base.html' %}

{% block title %}{{ '编辑' if exam else '创建' }}试卷 - 后台管理系统{% endblock %}

{% block nav_exams %}active{% endblock %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
    <h2>{{ '编辑' if exam else '创建' }}试卷</h2>
    <a href="{{ url_for('admin.exam_list') }}" class="btn btn-secondary">
        <i class="bi bi-arrow-left"></i> 返回列表
    </a>
</div>

<form method="post" class="needs-validation" enctype="multipart/form-data" novalidate>
    <!-- 基本信息 -->
    <div class="card mb-4">
        <div class="card-header">
            <h5 class="card-title mb-0">基本信息</h5>
        </div>
        <div class="card-body">
            <div class="row g-3">
                <div class="col-md-6">
                    <label for="name" class="form-label">试卷名称</label>
                    <input type="text" class="form-control" id="name" name="name" 
                           value="{{ exam.name if exam else '' }}" required>
                    <div class="invalid-feedback">
                        请输入试卷名称
                    </div>
                </div>
                
                <div class="col-md-3">
                    <label for="subject" class="form-label">科目</label>
                    <select class="form-select" id="subject" name="subject" required>
                        <option value="">请选择科目</option>
                        <option value="python" {% if exam and exam.subject == 'python' %}selected{% endif %}>Python</option>
                        <option value="scratch" {% if exam and exam.subject == 'scratch' %}selected{% endif %}>Scratch</option>
                    </select>
                    <div class="invalid-feedback">
                        请选择科目
                    </div>
                </div>
                
                <div class="col-md-3">
                    <label for="difficulty" class="form-label">难度等级</label>
                    <div class="difficulty-rating">
                        {% for i in range(1, 6) %}
                        <div class="form-check form-check-inline">
                            <input class="btn-check" type="radio" name="difficulty" 
                                   id="difficulty{{ i }}" value="{{ i }}" 
                                   {% if (exam and exam.difficulty == i) or (not exam and i == 1) %}checked{% endif %}>
                            <label class="btn btn-outline-warning" for="difficulty{{ i }}">
                                {{ i }}
                            </label>
                        </div>
                        {% endfor %}
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 试题管理 -->
    <div class="card mb-4">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="card-title mb-0">试题管理</h5>
            <button type="button" class="btn btn-primary btn-sm" id="addQuestionBtn">
                <i class="fas fa-plus"></i> 添加试题
            </button>
        </div>
        <div class="card-body">
            <div id="questionsContainer">
                {% if exam and exam.questions %}
                    {% for question in exam.questions %}
                    <div class="question-item card mb-3">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <div class="d-flex align-items-center">
                                <select class="form-select form-select-sm me-2" name="questions[{{ loop.index0 }}][type]" onchange="updateQuestionType(this)" style="width: 100px;">
                                    <option value="single" {% if question.type == 'single' %}selected{% endif %}>单选题</option>
                                    <option value="multiple" {% if question.type == 'multiple' %}selected{% endif %}>多选题</option>
                                    <option value="boolean" {% if question.type == 'boolean' %}selected{% endif %}>判断题</option>
                                </select>
                                <span class="badge bg-secondary question-number"></span>
                            </div>
                            <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeQuestion(this)">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                        <div class="card-body">
                            <div class="mb-3">
                                <div class="form-check form-switch mb-2">
                                    <input class="form-check-input question-image-toggle" type="checkbox" 
                                           id="question_has_image_{{ loop.index0 }}" data-index="{{ loop.index0 }}" 
                                           {% if question.has_image %}checked{% endif %}
                                           onchange="toggleQuestionImage(this)">
                                    <label class="form-check-label" for="question_has_image_{{ loop.index0 }}">添加图片</label>
                                </div>
                                <div class="question-image-container mb-3" style="display: {% if question.has_image %}block{% else %}none{% endif %};">
                                    <label class="form-label">题目图片</label>
                                    <input type="file" class="form-control" name="questions[{{ loop.index0 }}][image]" accept="image/*" onchange="previewImage(this)">
                                    {% if question.has_image and question.image_path %}
                                    <div class="mt-2 image-preview" style="max-width: 300px; display: block;">
                                        <img src="{{ question.image_path }}" class="img-fluid rounded border" alt="题目图片">
                                    </div>
                                    {% else %}
                                    <div class="mt-2 image-preview" style="max-width: 300px; display: none;">
                                        <img src="#" class="img-fluid rounded border" alt="预览图">
                                    </div>
                                    {% endif %}
                                    
                                    {% if question.has_image %}
                                    <input type="hidden" name="questions[{{ loop.index0 }}][has_image]" value="true" class="has-image-input">
                                    {% if question.image_path %}
                                    <input type="hidden" name="questions[{{ loop.index0 }}][original_image_path]" value="{{ question.image_path }}">
                                    {% endif %}
                                    {% endif %}
                                </div>
                                <label class="form-label">题目内容</label>
                                <textarea class="form-control" name="questions[{{ loop.index0 }}][title]" rows="2" required>{{ question.title }}</textarea>
                            </div>
                            
                            {% if question.type in ['single', 'multiple'] %}
                            <div class="options-container">
                                {% for option in question.options %}
                                <div class="input-group mb-2">
                                    <span class="input-group-text">{{ chr_function(65 + loop.index0) }}</span>
                                    <input type="text" class="form-control" name="questions[{{ loop.index0 }}][options][{{ loop.index0 }}]" value="{{ option }}" required>
                                    <div class="input-group-text">
                                        <input class="{{ 'form-check-input' if question.type == 'multiple' else '' }}" 
                                               type="{{ 'checkbox' if question.type == 'multiple' else 'radio' }}"
                                               name="questions[{{ loop.index0 }}][correct_answers][]"
                                               value="{{ loop.index0 }}"
                                               {% if loop.index0 in question.correct_answers %}checked{% endif %}>
                                    </div>
                                </div>
                                {% endfor %}
                            </div>
                            {% else %}
                            <div class="boolean-answer">
                                <label class="form-label">正确答案</label>
                                <div class="btn-group w-100">
                                    <input type="radio" class="btn-check" name="questions[{{ loop.index0 }}][correct_answer]" value="true" id="true_{{ loop.index }}"
                                           {% if question.correct_answers[0] %}checked{% endif %}>
                                    <label class="btn btn-outline-success" for="true_{{ loop.index }}">
                                        <i class="bi bi-check-lg"></i> 正确
                                    </label>
                                    <input type="radio" class="btn-check" name="questions[{{ loop.index0 }}][correct_answer]" value="false" id="false_{{ loop.index }}"
                                           {% if not question.correct_answers[0] %}checked{% endif %}>
                                    <label class="btn btn-outline-danger" for="false_{{ loop.index }}">
                                        <i class="bi bi-x-lg"></i> 错误
                                    </label>
                                </div>
                            </div>
                            {% endif %}
                        </div>
                    </div>
                    {% endfor %}
                {% endif %}
            </div>
        </div>
    </div>

    <!-- 提交按钮 -->
    <div class="text-end">
        <button type="submit" class="btn btn-primary">
            <i class="bi bi-save"></i> 保存试卷
        </button>
    </div>
</form>

<!-- 试题模板 -->
<template id="questionTemplate">
    <div class="question-item card mb-3">
        <div class="card-header d-flex justify-content-between align-items-center">
            <div class="d-flex align-items-center">
                <select class="form-select form-select-sm me-2" name="questions[0][type]" onchange="updateQuestionType(this)" style="width: 100px;">
                    <option value="single">单选题</option>
                    <option value="multiple">多选题</option>
                    <option value="boolean">判断题</option>
                </select>
                <span class="badge bg-secondary question-number"></span>
            </div>
            <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeQuestion(this)">
                <i class="fas fa-trash"></i>
            </button>
        </div>
        <div class="card-body">
            <div class="mb-3">
                <div class="form-check form-switch mb-2">
                    <input class="form-check-input question-image-toggle" type="checkbox" 
                           id="question_has_image_0" data-index="0" onchange="toggleQuestionImage(this)">
                    <label class="form-check-label" for="question_has_image_0">添加图片</label>
                </div>
                <div class="question-image-container mb-3" style="display: none;">
                    <label class="form-label">题目图片</label>
                    <input type="file" class="form-control" name="questions[0][image]" accept="image/*" onchange="previewImage(this)">
                    <div class="mt-2 image-preview" style="max-width: 300px; display: none;">
                        <img src="#" class="img-fluid rounded border" alt="预览图">
                    </div>
                </div>
                <label class="form-label">题目内容</label>
                <textarea class="form-control" name="questions[0][title]" rows="2" required></textarea>
            </div>
            <div class="options-container">
                <!-- 选项容器 -->
            </div>
        </div>
    </div>
</template>

<script>
// 添加试题
document.getElementById('addQuestionBtn').addEventListener('click', function() {
    const container = document.getElementById('questionsContainer');
    const template = document.getElementById('questionTemplate');
    const clone = template.content.cloneNode(true);
    
    // 获取当前题目索引
    const currentIndex = document.querySelectorAll('.question-item').length;
    
    // 更新克隆元素中的name属性
    const select = clone.querySelector('select');
    const textarea = clone.querySelector('textarea');
    const imageInput = clone.querySelector('input[type="file"]');
    const imageToggle = clone.querySelector('.question-image-toggle');
    
    select.name = `questions[${currentIndex}][type]`;
    textarea.name = `questions[${currentIndex}][title]`;
    imageInput.name = `questions[${currentIndex}][image]`;
    imageToggle.id = `question_has_image_${currentIndex}`;
    imageToggle.setAttribute('data-index', currentIndex);
    
    // 初始化为单选题
    const optionsContainer = clone.querySelector('.options-container');
    
    // 添加选项
    const options = ['A', 'B', 'C', 'D'];
    options.forEach((letter, idx) => {
        const optionDiv = document.createElement('div');
        optionDiv.className = 'input-group mb-2';
        optionDiv.innerHTML = `
            <span class="input-group-text">${letter}</span>
            <input type="text" class="form-control" name="questions[${currentIndex}][options][${idx}]" required>
            <div class="input-group-text">
                <input type="radio" class="form-check-input" 
                       name="questions[${currentIndex}][correct_answers][]" 
                       value="${idx}" required>
            </div>
        `;
        optionsContainer.appendChild(optionDiv);
    });
    
    // 添加到容器
    container.appendChild(clone);
    updateQuestionNumbers();
});

// 更新题号
function updateQuestionNumbers() {
    const questions = document.querySelectorAll('.question-item');
    questions.forEach((question, index) => {
        const badge = question.querySelector('.question-number');
        if (badge) {
            badge.textContent = `第 ${index + 1} 题`;
        }
        
        // 更新所有表单字段的索引
        const select = question.querySelector('select');
        const textarea = question.querySelector('textarea');
        const options = question.querySelectorAll('input[type="text"]');
        const answers = question.querySelectorAll('input[type="radio"], input[type="checkbox"]');
        const imageInput = question.querySelector('input[type="file"]');
        const imageToggle = question.querySelector('.question-image-toggle');
        
        select.name = `questions[${index}][type]`;
        textarea.name = `questions[${index}][title]`;
        imageInput.name = `questions[${index}][image]`;
        imageToggle.id = `question_has_image_${index}`;
        imageToggle.setAttribute('data-index', index);
        
        options.forEach((option, optionIndex) => {
            option.name = `questions[${index}][options][${optionIndex}]`;
        });
        
        const type = select.value;
        if (type === 'boolean') {
            answers.forEach(answer => {
                answer.name = `questions[${index}][correct_answer]`;
            });
        } else {
            answers.forEach(answer => {
                answer.name = `questions[${index}][correct_answers][]`;
            });
        }
    });
}

// 删除试题
function removeQuestion(button) {
    const questionItem = button.closest('.question-item');
    questionItem.remove();
    updateQuestionNumbers();
}

// 更新试题类型
function updateQuestionType(select) {
    const questionItem = select.closest('.question-item');
    const optionsContainer = questionItem.querySelector('.options-container');
    const type = select.value;
    const index = Array.from(document.querySelectorAll('.question-item')).indexOf(questionItem);
    
    // 清空选项容器
    optionsContainer.innerHTML = '';
    
    if (type === 'boolean') {
        // 判断题选项
        const options = ['正确', '错误'];
        options.forEach((text, idx) => {
            const optionDiv = document.createElement('div');
            optionDiv.className = 'input-group mb-2';
            optionDiv.innerHTML = `
                <span class="input-group-text">${idx + 1}</span>
                <input type="text" class="form-control" name="questions[${index}][options][${idx}]" value="${text}" readonly>
                <div class="input-group-text">
                    <input type="radio" class="form-check-input" 
                           name="questions[${index}][correct_answers][]" 
                           value="${idx}" required>
                </div>
            `;
            optionsContainer.appendChild(optionDiv);
        });
    } else if (type === 'single') {
        // 单选题选项
        const options = ['A', 'B', 'C', 'D'];
        options.forEach((letter, idx) => {
            const optionDiv = document.createElement('div');
            optionDiv.className = 'input-group mb-2';
            optionDiv.innerHTML = `
                <span class="input-group-text">${letter}</span>
                <input type="text" class="form-control" name="questions[${index}][options][${idx}]" required>
                <div class="input-group-text">
                    <input type="radio" class="form-check-input" 
                           name="questions[${index}][correct_answers][]" 
                           value="${idx}" required>
                </div>
            `;
            optionsContainer.appendChild(optionDiv);
        });
    } else if (type === 'multiple') {
        // 多选题选项
        const options = ['A', 'B', 'C', 'D'];
        options.forEach((letter, idx) => {
            const optionDiv = document.createElement('div');
            optionDiv.className = 'input-group mb-2';
            optionDiv.innerHTML = `
                <span class="input-group-text">${letter}</span>
                <input type="text" class="form-control" name="questions[${index}][options][${idx}]" required>
                <div class="input-group-text">
                    <input type="checkbox" class="form-check-input" 
                           name="questions[${index}][correct_answers][]" 
                           value="${idx}">
                </div>
            `;
            optionsContainer.appendChild(optionDiv);
        });
    } else if (type === 'fill') {
        // 填空题
        const optionDiv = document.createElement('div');
        optionDiv.className = 'input-group mb-2';
        optionDiv.innerHTML = `
            <span class="input-group-text">答案</span>
            <input type="text" class="form-control" name="questions[${index}][correct_answers]" required>
        `;
        optionsContainer.appendChild(optionDiv);
    }
}

// 图片预览功能
function previewImage(input) {
    const preview = input.closest('.question-image-container').querySelector('.image-preview');
    const img = preview.querySelector('img');
    
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        
        reader.onload = function(e) {
            img.src = e.target.result;
            preview.style.display = 'block';
        }
        
        reader.readAsDataURL(input.files[0]);
    } else {
        img.src = '#';
        preview.style.display = 'none';
    }
}

// 切换图片上传功能
function toggleQuestionImage(checkbox) {
    const questionItem = checkbox.closest('.question-item');
    const imageContainer = questionItem.querySelector('.question-image-container');
    const index = checkbox.getAttribute('data-index');
    
    if (checkbox.checked) {
        imageContainer.style.display = 'block';
        
        // 添加一个隐藏的输入字段来标记该题有图片
        const hiddenInput = document.createElement('input');
        hiddenInput.type = 'hidden';
        hiddenInput.name = `questions[${index}][has_image]`;
        hiddenInput.value = 'true';
        hiddenInput.classList.add('has-image-input');
        questionItem.appendChild(hiddenInput);
    } else {
        imageContainer.style.display = 'none';
        
        // 移除隐藏的输入字段
        const hiddenInput = questionItem.querySelector('.has-image-input');
        if (hiddenInput) {
            hiddenInput.remove();
        }
        
        // 清空文件输入
        const fileInput = imageContainer.querySelector('input[type="file"]');
        if (fileInput) {
            fileInput.value = '';
        }
        
        // 隐藏预览
        const preview = imageContainer.querySelector('.image-preview');
        if (preview) {
            preview.style.display = 'none';
        }
    }
}

// 页面加载时初始化题号
document.addEventListener('DOMContentLoaded', function() {
    updateQuestionNumbers();
});
</script>

<style>
.difficulty-rating .btn-check:checked + .btn {
    background-color: #ffc107;
    border-color: #ffc107;
    color: #000;
}

.question-item {
    position: relative;
    border: 1px solid #dee2e6;
}

.question-number {
    font-size: 0.9rem;
    margin-left: 10px;
}

.options-container {
    margin-top: 1rem;
}

.boolean-answer {
    margin-top: 1rem;
}

.boolean-answer .btn-group {
    gap: 10px;
}

.boolean-answer .btn {
    flex: 1;
}

.question-image-container {
    margin-top: 1rem;
}

.image-preview {
    margin-top: 1rem;
}
</style>
{% endblock %}

{% block extra_js %}
<script>
// 表单验证
(function () {
    'use strict'
    var forms = document.querySelectorAll('.needs-validation')
    Array.prototype.slice.call(forms).forEach(function (form) {
        form.addEventListener('submit', function (event) {
            if (!form.checkValidity()) {
                event.preventDefault()
                event.stopPropagation()
            }
            form.classList.add('was-validated')
        }, false)
    })
})()
</script>
{% endblock %}